

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/favicon.png">
  <link rel="icon" href="/img/favicon.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="John Doe">
  <meta name="keywords" content="">
  
    <meta name="description" content="Trait自 PHP 5.4.0 起，PHP 实现了一种代码复用的方法，称为 trait。  Trait 是为类似 PHP 的单继承语言而准备的一种代码复用机制。Trait 为了减少单继承语言的限制，使开发人员能够自由地在不同层次结构内独立的类中复用 method。Trait 和 Class 组合的语义定义了一种减少复杂性的方式，避免传统多继承和 Mixin 类相关典型问题。  Trait 和 C">
<meta property="og:type" content="article">
<meta property="og:title" content="Trait">
<meta property="og:url" content="http://example.com/2017/11/28/php/Trait%20/index.html">
<meta property="og:site_name" content="Hexo">
<meta property="og:description" content="Trait自 PHP 5.4.0 起，PHP 实现了一种代码复用的方法，称为 trait。  Trait 是为类似 PHP 的单继承语言而准备的一种代码复用机制。Trait 为了减少单继承语言的限制，使开发人员能够自由地在不同层次结构内独立的类中复用 method。Trait 和 Class 组合的语义定义了一种减少复杂性的方式，避免传统多继承和 Mixin 类相关典型问题。  Trait 和 C">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2017-11-27T16:00:00.000Z">
<meta property="article:modified_time" content="2022-02-10T03:11:29.796Z">
<meta property="article:author" content="John Doe">
<meta property="article:tag" content="PHP">
<meta name="twitter:card" content="summary_large_image">
  
  
  <title>Trait - Hexo</title>

  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/github-markdown-css@4/github-markdown.min.css" />
  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/hint.css@2/hint.min.css" />

  
    
    
      
      <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/highlight.js@10/styles/github-gist.min.css" />
    
  

  
    <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.css" />
  


<!-- 主题依赖的图标库，不要自行修改 -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_ba1fz6golrf.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/css/main.css" />

<!-- 自定义样式保持在最底部 -->


  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    var CONFIG = {"hostname":"example.com","root":"/","version":"1.8.13","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"right","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"copy_btn":true,"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/local-search.xml"};
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
<meta name="generator" content="Hexo 6.0.0"></head>


<body>
  <header style="height: 70vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>LZDF</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="banner" id="banner" parallax=true
         style="background: url('/img/default.png') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="page-header text-center fade-in-up">
            <span class="h2" id="subtitle" title="Trait">
              
            </span>

            
              <div class="mt-3">
  
  
    <span class="post-meta">
      <i class="iconfont icon-date-fill" aria-hidden="true"></i>
      <time datetime="2017-11-28 00:00" pubdate>
        2017年11月28日 凌晨
      </time>
    </span>
  
</div>

<div class="mt-1">
  
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      5.3k 字
    </span>
  

  
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      44 分钟
    </span>
  

  
  
</div>

            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div class="py-5" id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">Trait</h1>
            
            <div class="markdown-body">
              <h1 id="Trait"><a href="#Trait" class="headerlink" title="Trait"></a>Trait</h1><p>自 PHP 5.4.0 起，PHP 实现了一种代码复用的方法，称为 trait。 </p>
<p>Trait 是为类似 PHP 的单继承语言而准备的一种代码复用机制。Trait 为了减少单继承语言的限制，使开发人员能够自由地在不同层次结构内独立的类中复用 method。Trait 和 Class 组合的语义定义了一种减少复杂性的方式，避免传统多继承和 Mixin 类相关典型问题。 </p>
<p>Trait 和 Class 相似，但仅仅旨在用细粒度和一致的方式来组合功能。 无法通过 trait 自身来实例化。它为传统继承增加了水平特性的组合；也就是说，应用的几个 Class 之间不需要继承。 </p>
<h2 id="Example-1-Trait-示例"><a href="#Example-1-Trait-示例" class="headerlink" title="Example #1 Trait 示例"></a>Example #1 Trait 示例</h2><figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><code class="hljs php"><span class="hljs-meta">&lt;?php</span><br><span class="hljs-class"><span class="hljs-keyword">trait</span> <span class="hljs-title">ezcReflectionReturnInfo</span> </span>&#123;<br>    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getReturnType</span>(<span class="hljs-params"></span>) </span>&#123; <span class="hljs-comment">/*1*/</span> &#125;<br>    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getReturnDescription</span>(<span class="hljs-params"></span>) </span>&#123; <span class="hljs-comment">/*2*/</span> &#125;<br>&#125;<br><br><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ezcReflectionMethod</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">ReflectionMethod</span> </span>&#123;<br>    <span class="hljs-keyword">use</span> <span class="hljs-title">ezcReflectionReturnInfo</span>;<br>    <span class="hljs-comment">/* ... */</span><br>&#125;<br><br><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ezcReflectionFunction</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">ReflectionFunction</span> </span>&#123;<br>    <span class="hljs-keyword">use</span> <span class="hljs-title">ezcReflectionReturnInfo</span>;<br>    <span class="hljs-comment">/* ... */</span><br>&#125;<br><span class="hljs-meta">?&gt;</span> <br></code></pre></td></tr></table></figure>
<h1 id="优先级"><a href="#优先级" class="headerlink" title="优先级"></a>优先级</h1><p>从基类继承的成员会被 trait 插入的成员所覆盖。优先顺序是来自当前类的成员覆盖了 trait 的方法，而 trait 则覆盖了被继承的方法。 </p>
<h2 id="Example-2-优先顺序示例"><a href="#Example-2-优先顺序示例" class="headerlink" title="Example #2 优先顺序示例"></a>Example #2 优先顺序示例</h2><p>从基类继承的成员被插入的 SayWorld Trait 中的 MyHelloWorld 方法所覆盖。其行为 MyHelloWorld 类中定义的方法一致。优先顺序是当前类中的方法会覆盖 trait 方法，而 trait 方法又覆盖了基类中的方法。 </p>
<figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><code class="hljs php"><span class="hljs-meta">&lt;?php</span><br><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Base</span> </span>&#123;<br>    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sayHello</span>(<span class="hljs-params"></span>) </span>&#123;<br>        <span class="hljs-keyword">echo</span> <span class="hljs-string">&#x27;Hello &#x27;</span>;<br>    &#125;<br>&#125;<br><br><span class="hljs-class"><span class="hljs-keyword">trait</span> <span class="hljs-title">SayWorld</span> </span>&#123;<br>    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sayHello</span>(<span class="hljs-params"></span>) </span>&#123;<br>        <span class="hljs-built_in">parent</span>::sayHello();<br>        <span class="hljs-keyword">echo</span> <span class="hljs-string">&#x27;World!&#x27;</span>;<br>    &#125;<br>&#125;<br><br><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyHelloWorld</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Base</span> </span>&#123;<br>    <span class="hljs-keyword">use</span> <span class="hljs-title">SayWorld</span>;<br>&#125;<br><br><span class="hljs-variable">$o</span> = <span class="hljs-keyword">new</span> MyHelloWorld();<br><span class="hljs-variable">$o</span>-&gt;sayHello();<br><span class="hljs-meta">?&gt;</span> <br><span class="hljs-comment">// 以上例程会输出：</span><br><span class="hljs-comment">//  Hello World!</span><br></code></pre></td></tr></table></figure>

<h2 id="Example-3-另一个优先级顺序的例子"><a href="#Example-3-另一个优先级顺序的例子" class="headerlink" title="Example #3 另一个优先级顺序的例子"></a>Example #3 另一个优先级顺序的例子</h2><figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><code class="hljs php"><span class="hljs-meta">&lt;?php</span><br><span class="hljs-class"><span class="hljs-keyword">trait</span> <span class="hljs-title">HelloWorld</span> </span>&#123;<br>    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sayHello</span>(<span class="hljs-params"></span>) </span>&#123;<br>        <span class="hljs-keyword">echo</span> <span class="hljs-string">&#x27;Hello World!&#x27;</span>;<br>    &#125;<br>&#125;<br><br><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">TheWorldIsNotEnough</span> </span>&#123;<br>    <span class="hljs-keyword">use</span> <span class="hljs-title">HelloWorld</span>;<br>    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sayHello</span>(<span class="hljs-params"></span>) </span>&#123;<br>        <span class="hljs-keyword">echo</span> <span class="hljs-string">&#x27;Hello Universe!&#x27;</span>;<br>    &#125;<br>&#125;<br><br><span class="hljs-variable">$o</span> = <span class="hljs-keyword">new</span> TheWorldIsNotEnough();<br><span class="hljs-variable">$o</span>-&gt;sayHello();<br><span class="hljs-meta">?&gt;</span> <br><span class="hljs-comment">// 以上例程会输出：</span><br><span class="hljs-comment">//  Hello Universe!</span><br></code></pre></td></tr></table></figure>

<h1 id="多个-trait"><a href="#多个-trait" class="headerlink" title="多个 trait"></a>多个 trait</h1><p>通过逗号分隔，在 use 声明列出多个 trait，可以都插入到一个类中。 </p>
<h2 id="Example-4-多个-trait-的用法"><a href="#Example-4-多个-trait-的用法" class="headerlink" title="Example #4 多个 trait 的用法"></a>Example #4 多个 trait 的用法</h2><figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><code class="hljs php"><span class="hljs-meta">&lt;?php</span><br><span class="hljs-class"><span class="hljs-keyword">trait</span> <span class="hljs-title">Hello</span> </span>&#123;<br>    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sayHello</span>(<span class="hljs-params"></span>) </span>&#123;<br>        <span class="hljs-keyword">echo</span> <span class="hljs-string">&#x27;Hello &#x27;</span>;<br>    &#125;<br>&#125;<br><br><span class="hljs-class"><span class="hljs-keyword">trait</span> <span class="hljs-title">World</span> </span>&#123;<br>    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sayWorld</span>(<span class="hljs-params"></span>) </span>&#123;<br>        <span class="hljs-keyword">echo</span> <span class="hljs-string">&#x27;World&#x27;</span>;<br>    &#125;<br>&#125;<br><br><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyHelloWorld</span> </span>&#123;<br>    <span class="hljs-keyword">use</span> <span class="hljs-title">Hello</span>, <span class="hljs-title">World</span>;<br>    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sayExclamationMark</span>(<span class="hljs-params"></span>) </span>&#123;<br>        <span class="hljs-keyword">echo</span> <span class="hljs-string">&#x27;!&#x27;</span>;<br>    &#125;<br>&#125;<br><br><span class="hljs-variable">$o</span> = <span class="hljs-keyword">new</span> MyHelloWorld();<br><span class="hljs-variable">$o</span>-&gt;sayHello();<br><span class="hljs-variable">$o</span>-&gt;sayWorld();<br><span class="hljs-variable">$o</span>-&gt;sayExclamationMark();<br><span class="hljs-meta">?&gt;</span> <br><span class="hljs-comment">// 以上例程会输出：</span><br><span class="hljs-comment">// Hello World!</span><br></code></pre></td></tr></table></figure>

<h2 id="冲突的解决"><a href="#冲突的解决" class="headerlink" title="冲突的解决"></a>冲突的解决</h2><p>如果两个 trait 都插入了一个同名的方法，如果没有明确解决冲突将会产生一个致命错误。 </p>
<p>为了解决多个 trait 在同一个类中的命名冲突，需要使用 insteadof 操作符来明确指定使用冲突方法中的哪一个。 </p>
<p>以上方式仅允许排除掉其它方法，as 操作符可以 为某个方法引入别名。 注意，as 操作符不会对方法进行重命名，也不会影响其方法。</p>
<h2 id="Example-5-冲突的解决"><a href="#Example-5-冲突的解决" class="headerlink" title="Example #5 冲突的解决"></a>Example #5 冲突的解决</h2><p>在本例中 Talker 使用了 trait A 和 B。由于 A 和 B 有冲突的方法，其定义了使用 trait B 中的 smallTalk 以及 trait A 中的 bigTalk。 </p>
<p>Aliased_Talker 使用了 as 操作符来定义了 talk 来作为 B 的 bigTalk 的别名。 </p>
<figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><code class="hljs php"><span class="hljs-meta">&lt;?php</span><br><span class="hljs-class"><span class="hljs-keyword">trait</span> <span class="hljs-title">A</span> </span>&#123;<br>    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">smallTalk</span>(<span class="hljs-params"></span>) </span>&#123;<br>        <span class="hljs-keyword">echo</span> <span class="hljs-string">&#x27;a&#x27;</span>;<br>    &#125;<br>    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">bigTalk</span>(<span class="hljs-params"></span>) </span>&#123;<br>        <span class="hljs-keyword">echo</span> <span class="hljs-string">&#x27;A&#x27;</span>;<br>    &#125;<br>&#125;<br><br><span class="hljs-class"><span class="hljs-keyword">trait</span> <span class="hljs-title">B</span> </span>&#123;<br>    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">smallTalk</span>(<span class="hljs-params"></span>) </span>&#123;<br>        <span class="hljs-keyword">echo</span> <span class="hljs-string">&#x27;b&#x27;</span>;<br>    &#125;<br>    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">bigTalk</span>(<span class="hljs-params"></span>) </span>&#123;<br>        <span class="hljs-keyword">echo</span> <span class="hljs-string">&#x27;B&#x27;</span>;<br>    &#125;<br>&#125;<br><br><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Talker</span> </span>&#123;<br>    <span class="hljs-keyword">use</span> <span class="hljs-title">A</span>, <span class="hljs-title">B</span> &#123;<br>        <span class="hljs-title">B</span>::<span class="hljs-title">smallTalk</span> <span class="hljs-title">insteadof</span> <span class="hljs-title">A</span>;<br>        A::bigTalk <span class="hljs-keyword">insteadof</span> B;<br>    &#125;<br>&#125;<br><br><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Aliased_Talker</span> </span>&#123;<br>    <span class="hljs-keyword">use</span> <span class="hljs-title">A</span>, <span class="hljs-title">B</span> &#123;<br>        <span class="hljs-title">B</span>::<span class="hljs-title">smallTalk</span> <span class="hljs-title">insteadof</span> <span class="hljs-title">A</span>;<br>        A::bigTalk <span class="hljs-keyword">insteadof</span> B;<br>        B::bigTalk <span class="hljs-keyword">as</span> talk;<br>    &#125;<br>&#125;<br><span class="hljs-meta">?&gt;</span> <br></code></pre></td></tr></table></figure>
<p class="note">
Note: 

<p>在 PHP 7.0 之前，在类里定义和 trait 同名的属性，哪怕是完全兼容的也会抛出 E_STRICT（完全兼容的意思：具有相同的访问可见性、初始默认值）。 </p>
</p>

<h1 id="修改方法的访问控制"><a href="#修改方法的访问控制" class="headerlink" title="修改方法的访问控制"></a>修改方法的访问控制</h1><p>使用 as 语法还可以用来调整方法的访问控制。 </p>
<h2 id="Example-6-修改方法的访问控制"><a href="#Example-6-修改方法的访问控制" class="headerlink" title="Example #6 修改方法的访问控制"></a>Example #6 修改方法的访问控制</h2><figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><code class="hljs php"><span class="hljs-meta">&lt;?php</span><br><span class="hljs-class"><span class="hljs-keyword">trait</span> <span class="hljs-title">HelloWorld</span> </span>&#123;<br>    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sayHello</span>(<span class="hljs-params"></span>) </span>&#123;<br>        <span class="hljs-keyword">echo</span> <span class="hljs-string">&#x27;Hello World!&#x27;</span>;<br>    &#125;<br>&#125;<br><br><span class="hljs-comment">// 修改 sayHello 的访问控制</span><br><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyClass1</span> </span>&#123;<br>    <span class="hljs-keyword">use</span> <span class="hljs-title">HelloWorld</span> &#123; <span class="hljs-title">sayHello</span> <span class="hljs-title">as</span> <span class="hljs-title">protected</span>; &#125;<br>&#125;<br><br><span class="hljs-comment">// 给方法一个改变了访问控制的别名</span><br><span class="hljs-comment">// 原版 sayHello 的访问控制则没有发生变化</span><br><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyClass2</span> </span>&#123;<br>    <span class="hljs-keyword">use</span> <span class="hljs-title">HelloWorld</span> &#123; <span class="hljs-title">sayHello</span> <span class="hljs-title">as</span> <span class="hljs-title">private</span> <span class="hljs-title">myPrivateHello</span>; &#125;<br>&#125;<br><span class="hljs-meta">?&gt;</span> <br></code></pre></td></tr></table></figure>

<h1 id="从-trait-来组成-trait"><a href="#从-trait-来组成-trait" class="headerlink" title="从 trait 来组成 trait"></a>从 trait 来组成 trait</h1><p>正如 class 能够使用 trait 一样，其它 trait 也能够使用 trait。在 trait 定义时通过使用一个或多个 trait，能够组合其它 trait 中的部分或全部成员。 </p>
<h2 id="Example-7-从-trait-来组成-trait"><a href="#Example-7-从-trait-来组成-trait" class="headerlink" title="Example #7 从 trait 来组成 trait"></a>Example #7 从 trait 来组成 trait</h2><figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><code class="hljs php"><span class="hljs-meta">&lt;?php</span><br><span class="hljs-class"><span class="hljs-keyword">trait</span> <span class="hljs-title">Hello</span> </span>&#123;<br>    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sayHello</span>(<span class="hljs-params"></span>) </span>&#123;<br>        <span class="hljs-keyword">echo</span> <span class="hljs-string">&#x27;Hello &#x27;</span>;<br>    &#125;<br>&#125;<br><br><span class="hljs-class"><span class="hljs-keyword">trait</span> <span class="hljs-title">World</span> </span>&#123;<br>    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sayWorld</span>(<span class="hljs-params"></span>) </span>&#123;<br>        <span class="hljs-keyword">echo</span> <span class="hljs-string">&#x27;World!&#x27;</span>;<br>    &#125;<br>&#125;<br><br><span class="hljs-class"><span class="hljs-keyword">trait</span> <span class="hljs-title">HelloWorld</span> </span>&#123;<br>    <span class="hljs-keyword">use</span> <span class="hljs-title">Hello</span>, <span class="hljs-title">World</span>;<br>&#125;<br><br><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyHelloWorld</span> </span>&#123;<br>    <span class="hljs-keyword">use</span> <span class="hljs-title">HelloWorld</span>;<br>&#125;<br><br><span class="hljs-variable">$o</span> = <span class="hljs-keyword">new</span> MyHelloWorld();<br><span class="hljs-variable">$o</span>-&gt;sayHello();<br><span class="hljs-variable">$o</span>-&gt;sayWorld();<br><span class="hljs-meta">?&gt;</span> <br><span class="hljs-comment">// Hello World!</span><br></code></pre></td></tr></table></figure>
<h1 id="Trait-的抽象成员"><a href="#Trait-的抽象成员" class="headerlink" title="Trait 的抽象成员"></a>Trait 的抽象成员</h1><p>为了对使用的类施加强制要求，trait 支持抽象方法的使用。 </p>
<h2 id="Example-8-表示通过抽象方法来进行强制要求"><a href="#Example-8-表示通过抽象方法来进行强制要求" class="headerlink" title="Example #8 表示通过抽象方法来进行强制要求"></a>Example #8 表示通过抽象方法来进行强制要求</h2><figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><code class="hljs php"><span class="hljs-meta">&lt;?php</span><br><span class="hljs-class"><span class="hljs-keyword">trait</span> <span class="hljs-title">Hello</span> </span>&#123;<br>    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sayHelloWorld</span>(<span class="hljs-params"></span>) </span>&#123;<br>        <span class="hljs-keyword">echo</span> <span class="hljs-string">&#x27;Hello&#x27;</span>.<span class="hljs-keyword">$this</span>-&gt;getWorld();<br>    &#125;<br>    <span class="hljs-keyword">abstract</span> <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getWorld</span>(<span class="hljs-params"></span>)</span>;<br>&#125;<br><br><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyHelloWorld</span> </span>&#123;<br>    <span class="hljs-keyword">private</span> <span class="hljs-variable">$world</span>;<br>    <span class="hljs-keyword">use</span> <span class="hljs-title">Hello</span>;<br>    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getWorld</span>(<span class="hljs-params"></span>) </span>&#123;<br>        <span class="hljs-keyword">return</span> <span class="hljs-keyword">$this</span>-&gt;world;<br>    &#125;<br>    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">setWorld</span>(<span class="hljs-params"><span class="hljs-variable">$val</span></span>) </span>&#123;<br>        <span class="hljs-keyword">$this</span>-&gt;world = <span class="hljs-variable">$val</span>;<br>    &#125;<br>&#125;<br><span class="hljs-meta">?&gt;</span> <br></code></pre></td></tr></table></figure>

<h1 id="Trait-的静态成员"><a href="#Trait-的静态成员" class="headerlink" title="Trait 的静态成员"></a>Trait 的静态成员</h1><p>Traits 可以被静态成员静态方法定义。 </p>
<h2 id="Example-9-静态变量"><a href="#Example-9-静态变量" class="headerlink" title="Example #9 静态变量"></a>Example #9 静态变量</h2><figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><code class="hljs php"><span class="hljs-meta">&lt;?php</span><br><span class="hljs-class"><span class="hljs-keyword">trait</span> <span class="hljs-title">Counter</span> </span>&#123;<br>    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">inc</span>(<span class="hljs-params"></span>) </span>&#123;<br>        <span class="hljs-built_in">static</span> <span class="hljs-variable">$c</span> = <span class="hljs-number">0</span>;<br>        <span class="hljs-variable">$c</span> = <span class="hljs-variable">$c</span> + <span class="hljs-number">1</span>;<br>        <span class="hljs-keyword">echo</span> <span class="hljs-string">&quot;<span class="hljs-subst">$c</span>\n&quot;</span>;<br>    &#125;<br>&#125;<br><br><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">C1</span> </span>&#123;<br>    <span class="hljs-keyword">use</span> <span class="hljs-title">Counter</span>;<br>&#125;<br><br><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">C2</span> </span>&#123;<br>    <span class="hljs-keyword">use</span> <span class="hljs-title">Counter</span>;<br>&#125;<br><br><span class="hljs-variable">$o</span> = <span class="hljs-keyword">new</span> C1(); <span class="hljs-variable">$o</span>-&gt;inc(); <span class="hljs-comment">// echo 1</span><br><span class="hljs-variable">$p</span> = <span class="hljs-keyword">new</span> C2(); <span class="hljs-variable">$p</span>-&gt;inc(); <span class="hljs-comment">// echo 1</span><br><span class="hljs-meta">?&gt;</span> <br></code></pre></td></tr></table></figure>

<h2 id="Example-10-静态方法"><a href="#Example-10-静态方法" class="headerlink" title="Example #10 静态方法"></a>Example #10 静态方法</h2><figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><code class="hljs php"><span class="hljs-meta">&lt;?php</span><br><span class="hljs-class"><span class="hljs-keyword">trait</span> <span class="hljs-title">StaticExample</span> </span>&#123;<br>    <span class="hljs-keyword">public</span> <span class="hljs-built_in">static</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">doSomething</span>(<span class="hljs-params"></span>) </span>&#123;<br>        <span class="hljs-keyword">return</span> <span class="hljs-string">&#x27;Doing something&#x27;</span>;<br>    &#125;<br>&#125;<br><br><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Example</span> </span>&#123;<br>    <span class="hljs-keyword">use</span> <span class="hljs-title">StaticExample</span>;<br>&#125;<br><br>Example::doSomething();<br><span class="hljs-meta">?&gt;</span> <br></code></pre></td></tr></table></figure>

<h1 id="属性"><a href="#属性" class="headerlink" title="属性"></a>属性</h1><p>Trait 同样可以定义属性。 </p>
<h2 id="Example-11-定义属性"><a href="#Example-11-定义属性" class="headerlink" title="Example #11 定义属性"></a>Example #11 定义属性</h2><figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><code class="hljs php"><span class="hljs-meta">&lt;?php</span><br><span class="hljs-class"><span class="hljs-keyword">trait</span> <span class="hljs-title">PropertiesTrait</span> </span>&#123;<br>    <span class="hljs-keyword">public</span> <span class="hljs-variable">$x</span> = <span class="hljs-number">1</span>;<br>&#125;<br><br><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">PropertiesExample</span> </span>&#123;<br>    <span class="hljs-keyword">use</span> <span class="hljs-title">PropertiesTrait</span>;<br>&#125;<br><br><span class="hljs-variable">$example</span> = <span class="hljs-keyword">new</span> PropertiesExample;<br><span class="hljs-variable">$example</span>-&gt;x;<br><span class="hljs-meta">?&gt;</span> <br></code></pre></td></tr></table></figure>

<p>Trait 定义了一个属性后，类就不能定义同样名称的属性，否则会产生 fatal error。 有种情况例外：属性是兼容的（同样的访问可见度、初始默认值）。 在 PHP 7.0 之前，属性是兼容的，则会有 E_STRICT 的提醒。 </p>
<h2 id="Example-12-解决冲突"><a href="#Example-12-解决冲突" class="headerlink" title="Example #12 解决冲突"></a>Example #12 解决冲突</h2><figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><code class="hljs php"><span class="hljs-meta">&lt;?php</span><br><span class="hljs-class"><span class="hljs-keyword">trait</span> <span class="hljs-title">PropertiesTrait</span> </span>&#123;<br>    <span class="hljs-keyword">public</span> <span class="hljs-variable">$same</span> = <span class="hljs-literal">true</span>;<br>    <span class="hljs-keyword">public</span> <span class="hljs-variable">$different</span> = <span class="hljs-literal">false</span>;<br>&#125;<br><br><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">PropertiesExample</span> </span>&#123;<br>    <span class="hljs-keyword">use</span> <span class="hljs-title">PropertiesTrait</span>;<br>    <span class="hljs-keyword">public</span> <span class="hljs-variable">$same</span> = <span class="hljs-literal">true</span>; <span class="hljs-comment">// PHP 7.0.0 后没问题，之前版本是 E_STRICT 提醒</span><br>    <span class="hljs-keyword">public</span> <span class="hljs-variable">$different</span> = <span class="hljs-literal">true</span>; <span class="hljs-comment">// 致命错误</span><br>&#125;<br><span class="hljs-meta">?&gt;</span> <br></code></pre></td></tr></table></figure>




            </div>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                  <div class="post-meta mr-3">
                    <i class="iconfont icon-category"></i>
                    
                      <a class="hover-with-bg" href="/categories/PHP/">PHP</a>
                    
                  </div>
                
                
                  <div class="post-meta">
                    <i class="iconfont icon-tags"></i>
                    
                      <a class="hover-with-bg" href="/tags/PHP/">PHP</a>
                    
                  </div>
                
              </div>
              
                <p class="note note-warning">
                  
                    本博客所有文章除特别声明外，均采用 <a target="_blank" href="https://creativecommons.org/licenses/by-sa/4.0/deed.zh" rel="nofollow noopener noopener">CC BY-SA 4.0 协议</a> ，转载请注明出处！
                  
                </p>
              
              
                <div class="post-prevnext">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2018/10/23/php/PHP%E9%80%92%E5%BD%92%E5%88%A0%E9%99%A4%E6%95%B0%E7%BB%84%E4%B8%AD%E5%80%BC%E4%B8%BA%E7%A9%BA%E7%9A%84%E5%85%83%E7%B4%A0/">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">PHP递归删除数组中值为空的元素.md</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2017/11/15/php/%E5%90%84%E7%B1%BB%20HTTP%20%E8%BF%94%E5%9B%9E%E7%8A%B6%E6%80%81%E4%BB%A3%E7%A0%81%E8%AF%A6%E8%A7%A3/">
                        <span class="hidden-mobile">【转】各类 HTTP 返回状态代码详解</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
    

    
  </main>

  <footer class="text-center mt-5 py-3">
  <div class="footer-content">
     <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
  </div>
  

  

  
</footer>


  <!-- SCRIPTS -->
  
  <script  src="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://cdn.jsdelivr.net/npm/jquery@3/dist/jquery.min.js" ></script>
<script  src="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>

<!-- Plugins -->


  <script  src="/js/local-search.js" ></script>



  
    <script  src="/js/img-lazyload.js" ></script>
  



  



  
    <script  src="https://cdn.jsdelivr.net/npm/tocbot@4/dist/tocbot.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/anchor-js@4/anchor.min.js" ></script>
  
  
    <script defer src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js" ></script>
  






  <script  src="https://cdn.jsdelivr.net/npm/typed.js@2/lib/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var title = document.getElementById('subtitle').title;
      
        typing(title);
      
    })(window, document);
  </script>















<!-- 主题的启动项 保持在最底部 -->
<script  src="/js/boot.js" ></script>


</body>
</html>
